﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Manager.Tools.NamedCheckconf
{
    /// <summary>
    /// named configuration file syntax checking tool configuration form
    /// </summary>
    public partial class NamedCheckconfForm : Form
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedCheckconfForm"/> class.
        /// </summary>
        public NamedCheckconfForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Click event of the checkButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void checkButton_Click(object sender, EventArgs e)
        {
            string checkPath = Path.Combine(Properties.Settings.Default.BindDirectoryPath, @"bin\named-checkconf.exe");
            string argument = GetArguments();
            string[] arguments = {checkPath, argument};
            checkButton.Enabled = false;

            checkExecuterBackgroundWorker.RunWorkerAsync(arguments);
        }

        /// <summary>
        /// Gets the arguments.
        /// </summary>
        /// <returns></returns>
        private string GetArguments()
        {
            StringBuilder argumentBuilder = new StringBuilder(20);
            if(versionCheckBox.Checked)
            {
                argumentBuilder.Append("-v ");
            }
            if(journalCheckBox.Checked)
            {
                argumentBuilder.Append("-j ");
            }
            if(!string.IsNullOrEmpty(directoryTextBox.Text))
            {
                argumentBuilder.AppendFormat("-t \"{0}\" ", directoryTextBox.Text);
            }
            if(!string.IsNullOrEmpty(filenameTextBox.Text))
            {
                argumentBuilder.Append(filenameTextBox.Text);
            }
            if(loadTestCheckBox.Checked)
            {
                argumentBuilder.Append("-z ");
            }

            return argumentBuilder.ToString();
        }

        /// <summary>
        /// Handles the DoWork event of the checkExecuterBackgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
        private void checkExecuterBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] arguments = (string[])e.Argument;

            ProcessStartInfo startInfo = new ProcessStartInfo(arguments[0], arguments[1]);
            startInfo.CreateNoWindow = true;
            startInfo.ErrorDialog = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;

            Process checkProcess = null;
            try
            {
                checkProcess = Process.Start(startInfo);

                string result;
                using (StreamReader reader = checkProcess.StandardOutput)
                {
                    result = reader.ReadToEnd();
                }
                result = result.Replace("\n", "\r\n");
                

                if(string.IsNullOrEmpty(result))
                {
                    e.Result = "Configuration file is in correct syntax.";
                }
                else
                {
                    e.Result = result;
                }
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Failed to check configuration file syntax.", ex);
            }
        }

        private void checkExecuterBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            resultTextBox.Text = e.Result.ToString();
            checkButton.Enabled = true;
        }

        /// <summary>
        /// Handles the Click event of the directoryBrowserButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void directoryBrowserButton_Click(object sender, EventArgs e)
        {
            if(directoryFolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                directoryTextBox.Text = directoryFolderBrowserDialog.SelectedPath;
            }
        }

        /// <summary>
        /// Handles the Click event of the filenameBrowserButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void filenameBrowserButton_Click(object sender, EventArgs e)
        {
            if(filenameOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                filenameTextBox.Text = filenameOpenFileDialog.FileName;
            }
        }
    }
}
